/*
*********************************************************************************************************
*                                               uC/OS-II
*                                         The Real-Time Kernel
*
*                        (c) Copyright 1992-1998, Jean J. Labrosse, Plantation, FL
*                                          All Rights Reserved
*
*
*                                       80x86/80x88 Specific code
*                                          LARGE MEMORY MODEL
*
* File : OS_CPU_C.C
* By   : Jean J. Labrosse
*
* Ported date:     Dec 2, 2001
* By:              John X. Liu, China, (johnxliu@163.com)
* Target platform: Keil C51 V6.20
*         
* Revision:        
*     DEC 5, 2001  Add supports for uC/OS II V2.51
*                  Changed the context saving sequence so that the ISRs can be writen in c language.
*                  and now, the OSTickISR and a serial interrupt sample have been included in this file
*                  to show how to write ISRs in c and keep compatible with uC/OS II.
*********************************************************************************************************
*/

#define  OS_CPU_GLOBALS
#include "includes.h"
#include "os_kcdef.h"
//sbit TEST=P1^7;
/*
*********************************************************************************************************
*                                        INITIALIZE A TASK'S STACK
*
* Description: This function is called by either OSTaskCreate() or OSTaskCreateExt() to initialize the
*              stack frame of the task being created.  This function is highly processor specific.
*
* Arguments  : task          is a pointer to the task code
*
*              pdata         is a pointer to a user supplied data area that will be passed to the task
*                            when the task first executes.
*
*              ptos          is a pointer to the top of stack.  It is assumed that 'ptos' points to
*                            a 'free' entry on the task stack.  If OS_STK_GROWTH is set to 1 then 
*                            'ptos' will contain the HIGHEST valid address of the stack.  Similarly, if
*                            OS_STK_GROWTH is set to 0, the 'ptos' will contains the LOWEST valid address
*                            of the stack.
*
*              opt           specifies options that can be used to alter the behavior of OSTaskStkInit().
*                            (see uCOS_II.H for OS_TASK_OPT_???).
*
* Returns    : Always returns the location of the new top-of-stack' once the processor registers have
*              been placed on the stack in the proper order.
*
* Note(s)    : Interrupts are enabled when your task starts executing. You can change this by setting the
*              PSW to 0x0002 instead.  In this case, interrupts would be disabled upon task startup.  The
*              application code would be responsible for enabling interrupts at the beginning of the task
*              code.  You will need to modify OSTaskIdle() and OSTaskStat() so that they enable 
*              interrupts.  Failure to do this will make your system crash!
*********************************************************************************************************
*/

/* The stack variable points to the start pointer in hardware stack and is defined in OS_CPU_A */
extern idata unsigned char Stack[1];

OS_STK *OSTaskStkInit (void (*task)(void *pd) KCREENTRANT, void * vd, OS_STK *ptos, INT16U opt) KCREENTRANT
{
    INT8U * stk;

    opt    = opt;                           /* 'opt' is not used, prevent warning                      */
    stk    = (INT8U *) ptos;                /* Load stack pointer                                      */

	stk				-= sizeof(void *);		/* Save the vd to external stack */
	*(void**)stk	 = vd;                  /*                               */

	stk				-= sizeof(INT16U);      /* The value should be loaded to PC    */
	*(INT16U*)stk	 = (INT16U) task;       /* next time when this task is running */

	stk				-= sizeof(INT16U);      /* The value should be loaded to PC    */
	*(INT16U*)stk	 = (INT16U) task;       /* next time when this task is running */

/* Following is the registers pushed into hardware stack */
	*--stk			 = 'A';                 /* ACC */
	*--stk			 = 'B';                 /* B   */
	*--stk			 = 'H';                 /* DPH */
	*--stk			 = 'L';                 /* DPL */
	*--stk			 = PSW;					/* PSW */
	*--stk			 = 0;                   /* R0  */
/*
	*--stk			 = 1;                   // should be R1
	*--stk			 = 2;                   // should be R2
	*--stk			 = 3;                   // should be R3
*/
	stk				-= sizeof(void *);      /* Keil C uses R1,R2,R3 to pass the */
	*(void**)stk	 = vd;                  /* arguments of functions.          */

	*--stk			 = 4;                   /* R4  */
	*--stk			 = 5;                   /* R5  */
	*--stk			 = 6;                   /* R6  */
	*--stk			 = 7;                   /* R7  */

    *--stk           = 0x80;                /* IE, EA is enabled  */
/*
    Next is calculating the hardware stack pointer.
*/
    *--stk			 = (INT8U) Stack-1      /* Initial value when main was called    */
	                   +1                   /* IE */
	                   +8                   /* R0-R7, eight registers was saved      */
                       +5                   /* PSW, ACC, B, DPH, DPL, five registers */
                       +sizeof(INT16U)      /* The PC value to be loaded             */
                       +sizeof(INT16U)      /* The PC value to be loaded             */
					   ;

    return ((void *)stk);
}

OS_EXT  OS_TCB      *OSTCBHighRdy;                    /* Pointer to highest priority TCB ready to run  */

void LoadCtx() KCREENTRANT;   /* Save the current working registers to stack, defined in OS_CPU_A.ASM */

extern INT8U xdata * data C_XBP;

/*
***********************************************************************************************************
* OSStartHighRdy: START MULTITASKING
*     
* Duty:     a) Call OSTaskSwHook() then,
*           b) Set OSRunning to TRUE,
*           c) Switch to the highest priority task.
*
***********************************************************************************************************
*/
void OSStartHighRdy(void) KCREENTRANT
{
    OSTaskSwHook();
	OSRunning=1;

	C_XBP=OSTCBHighRdy->OSTCBStkPtr;

	LoadCtx();
}

/**********************************************************************************************************
* C_OSCtxSw is the c part of OSCtxSw.
* When control passes to this function, the processor registers have been saved in external stack
***********************************************************************************************************/
void C_OSCtxSw(void) KCREENTRANT
{
/*	Save processor registers; DONE in the OSCtxSw part in OS_CPU_ASM.ASM                                  */

/*	Save the current task's stack pointer into the current task's OS_TCB:  
		OSTCBCur->OSTCBStkPtr = Stack pointer;
	Call user definable OSTaskSwHook();                                    
	OSTCBCur  = OSTCBHighRdy;                                              
	OSPrioCur = OSPrioHighRdy;                                             
	Get the stack pointer of the task to resume:                           
		Stack pointer = OSTCBHighRdy->OSTCBStkPtr;
	Restore all processor registers from the new task's stack;             
	Execute a return from interrupt instruction;                           */

    OSTCBCur->OSTCBStkPtr = C_XBP;
    
	OSTaskSwHook();
    OSTCBCur  = OSTCBHighRdy;
    OSPrioCur = OSPrioHighRdy;

    C_XBP       = OSTCBCur->OSTCBStkPtr;
    LoadCtx();
}

INT8U data SaveSP;

void OSIntCtxSw(void) KCREENTRANT
{
#pragma ASM
	CLR	EA
    MOV	SP, SaveSP
#pragma ENDASM

    C_XBP=OSTCBCur->OSTCBStkPtr;

#pragma ASM
	EXTRN   CODE(_?KCOSCtxSw)
	MOV		A, #LOW  _?KCOSCtxSw
	PUSH	ACC
	MOV		A, #HIGH _?KCOSCtxSw
	PUSH	ACC
	RETI
#pragma ENDASM
}

void UserTickTimer(void) KCREENTRANT;

/* OSTickISR can be writen in c language now, so it is more easy for user to write code for their own */
// OStimetick : oscilloscope measure of OSTimeTick(); : 100 us (80-90 us), no prehemption possible
void OSTickISR(void) interrupt 5
{ 
TF2=0;

    OSIntEnter();					/* Must be called first at every hardware interrupt entry point */
    if(OSIntNesting==1)
	{
#pragma ASM
		PUSH IE
		CLR	 EA
		MOV	 SaveSP, SP
#pragma ENDASM
		EA=0;
        OSTCBCur->OSTCBStkPtr=C_XBP;	/* OSTCBCur->OSTCBStkPtr is free now, so it can be used to story the value of SP */
    }
    UserTickTimer();
				/* User functions can be called here. */
   	OSTimeTick();	
				/* Must be called during tick isr */
   	OSIntExit();					/* Must be called finally at every hardware interupt exit point */
    if(OSIntNesting==0)
	{
		EA=0;
        C_XBP=OSTCBCur->OSTCBStkPtr;
#pragma ASM
		MOV	 SP, SaveSP
		POP	 IE
#pragma ENDASM

	}

}

/* Sample user ISR: Serial communication */
/* If you want to write ISRs for your own, just do as following */
void SerialIntr(void) interrupt 4
{
/* Do this first */
    OSIntEnter();					/* Must be called first at every hardware interrupt entry point */
    if(OSIntNesting==1)                     /* Only at the outerest interrupt we do these. */
	{
#pragma ASM
		PUSH IE
		CLR	 EA
		MOV	 SaveSP, SP
#pragma ENDASM
		EA=0;
        OSTCBCur->OSTCBStkPtr=C_XBP;	/* OSTCBCur->OSTCBStkPtr is free now, so it can be used to story the value of SP */
    }


/* Next you can do something for yourself. */
//
//	DoSomeWorks();					/* User function can be called here. */	
//
    if(TI0)
	{
		TI0=0;
//		if(CharsToSend)
//		{
//		    SBUF=GetNextChar();
//		}
	}
	else if(RI0)
	{
	    RI0=0;
//		CharIn=SBUF;
	}


/* Finally, before exit from ISR, must do as following. */
   	OSIntExit();					/* Must be called finally at every hardware interupt exit point */
    if(OSIntNesting==0)
	{
		EA=0;
        C_XBP=OSTCBCur->OSTCBStkPtr;
#pragma ASM
		MOV	 SP, SaveSP
		POP	 IE
#pragma ENDASM
	}
}


/*$PAGE*/
#if OS_CPU_HOOKS_EN
/*
*********************************************************************************************************
*                                       OS INITIALIZATION HOOK
*                                            (BEGINNING)
*
* Description: This function is called by OSInit() at the beginning of OSInit().
*
* Arguments  : none
*
* Note(s)    : 1) Interrupts should be disabled during this call.
*********************************************************************************************************
*/
#if OS_VERSION > 203
void OSInitHookBegin (void) KCREENTRANT
{
}
#endif

/*
*********************************************************************************************************
*                                       OS INITIALIZATION HOOK
*                                               (END)
*
* Description: This function is called by OSInit() at the end of OSInit().
*
* Arguments  : none
*
* Note(s)    : 1) Interrupts should be disabled during this call.
*********************************************************************************************************
*/
#if OS_VERSION > 203
void OSInitHookEnd (void) KCREENTRANT
{
}
#endif


/*
*********************************************************************************************************
*                                          TASK CREATION HOOK
*
* Description: This function is called when a task is created.
*
* Arguments  : ptcb   is a pointer to the task control block of the task being created.
*
* Note(s)    : 1) Interrupts are disabled during this call.
*********************************************************************************************************
*/
void OSTaskCreateHook (OS_TCB *ptcb) KCREENTRANT
{
    ptcb = ptcb;                       /* Prevent compiler warning                                     */
}


/*
*********************************************************************************************************
*                                           TASK DELETION HOOK
*
* Description: This function is called when a task is deleted.
*
* Arguments  : ptcb   is a pointer to the task control block of the task being deleted.
*
* Note(s)    : 1) Interrupts are disabled during this call.
*********************************************************************************************************
*/
void OSTaskDelHook (OS_TCB *ptcb) KCREENTRANT
{
    ptcb = ptcb;                       /* Prevent compiler warning                                     */
}

/*
*********************************************************************************************************
*                                           TASK SWITCH HOOK
*
* Description: This function is called when a task switch is performed.  This allows you to perform other
*              operations during a context switch.
*
* Arguments  : none
*
* Note(s)    : 1) Interrupts are disabled during this call.
*              2) It is assumed that the global pointer 'OSTCBHighRdy' points to the TCB of the task that
*                 will be 'switched in' (i.e. the highest priority task) and, 'OSTCBCur' points to the 
*                 task being switched out (i.e. the preempted task).
*********************************************************************************************************
*/
void OSTaskSwHook (void) KCREENTRANT
{
}

/*
*********************************************************************************************************
*                                           STATISTIC TASK HOOK
*
* Description: This function is called every second by uC/OS-II's statistics task.  This allows your 
*              application to add functionality to the statistics task.
*
* Arguments  : none
*********************************************************************************************************
*/
void OSTaskStatHook (void) KCREENTRANT
{
}

/*
*********************************************************************************************************
*                                           OSTCBInit() HOOK
*
* Description: This function is called by OSTCBInit() after setting up most of the TCB.
*
* Arguments  : ptcb    is a pointer to the TCB of the task being created.
*
* Note(s)    : 1) Interrupts may or may not be ENABLED during this call.
*********************************************************************************************************
*/
#if OS_VERSION > 203
void OSTCBInitHook (OS_TCB *ptcb) KCREENTRANT
{
    ptcb = ptcb;                                           /* Prevent Compiler warning                 */
}
#endif


/*
*********************************************************************************************************
*                                               TICK HOOK
*
* Description: This function is called every tick.
*
* Arguments  : none
*
* Note(s)    : 1) Interrupts may or may not be ENABLED during this call.
*********************************************************************************************************
*/
void OSTimeTickHook (void) KCREENTRANT
{
}


/*
*********************************************************************************************************
*                                             IDLE TASK HOOK
*
* Description: This function is called by the idle task.  This hook has been added to allow you to do  
*              such things as STOP the CPU to conserve power.
*
* Arguments  : none
*
* Note(s)    : 1) Interrupts are enabled during this call.
*********************************************************************************************************
*/
#if OS_VERSION >= 251
void OSTaskIdleHook (void) KCREENTRANT
{
}
#endif

#endif
